<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件分享 - Snapan</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .container {
            width: 100%;
            max-width: 420px;
        }

        .share-card {
            background: #ffffff;
            border-radius: 20px;
            padding: 48px 40px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.08);
            animation: slideUp 0.4s ease-out;
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .header {
            text-align: center;
            margin-bottom: 40px;
        }

        .title {
            font-size: 24px;
            font-weight: 600;
            color: #1a202c;
            margin-bottom: 8px;
            letter-spacing: -0.5px;
        }

        .subtitle {
            color: #718096;
            font-size: 14px;
            font-weight: 400;
        }

        /* 密码输入区域 */
        .password-form {
            margin-bottom: 24px;
        }

        .password-inputs {
            display: flex;
            gap: 12px;
            justify-content: center;
            margin-bottom: 32px;
        }

        .password-input {
            width: 56px;
            height: 56px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            text-align: center;
            font-size: 28px;
            font-weight: 600;
            color: #2d3748;
            transition: all 0.2s ease;
            background: #f7fafc;
        }

        .password-input:focus {
            outline: none;
            border-color: #667eea;
            background: #ffffff;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
            transform: scale(1.05);
        }

        .password-input::placeholder {
            color: #cbd5e0;
        }

        /* 按钮样式 */
        .btn {
            width: 100%;
            padding: 14px 24px;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            letter-spacing: 0.3px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }

        .btn-primary:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
        }

        .btn-primary:active:not(:disabled) {
            transform: translateY(0);
        }

        .btn-primary:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* 文件信息区域 */
        .file-info {
            margin-bottom: 24px;
            padding: 32px 24px;
            background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
            border-radius: 16px;
            text-align: center;
            animation: fadeIn 0.4s ease-out;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .file-icon {
            font-size: 64px;
            margin-bottom: 16px;
            display: block;
        }

        .file-name {
            font-size: 18px;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 12px;
            word-break: break-all;
        }

        .file-meta {
            color: #718096;
            font-size: 13px;
            display: flex;
            justify-content: center;
            gap: 16px;
        }

        /* 有效期信息 */
        .expire-info {
            background: #fef3c7;
            border-radius: 12px;
            padding: 14px 20px;
            margin-bottom: 24px;
            font-size: 13px;
            color: #92400e;
            text-align: center;
            animation: fadeIn 0.4s ease-out;
        }

        .expire-info.expired {
            background: #fee2e2;
            color: #991b1b;
        }

        /* 下载按钮 */
        .download-btn {
            width: 100%;
            padding: 14px 24px;
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
            letter-spacing: 0.3px;
        }

        .download-btn:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4);
        }

        .download-btn:active:not(:disabled) {
            transform: translateY(0);
        }

        .download-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* 错误提示 */
        .error-message {
            background: #fee2e2;
            border-radius: 12px;
            padding: 32px 24px;
            margin: 40px 0;
            color: #991b1b;
            font-size: 16px;
            text-align: center;
            animation: shake 0.4s ease-out;
            font-weight: 500;
        }
        
        .error-message.no-share {
            margin-top: 60px;
        }

        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-8px); }
            75% { transform: translateX(8px); }
        }

        /* 加载状态 */
        .loading {
            text-align: center;
            padding: 60px 20px;
            color: #718096;
            font-size: 15px;
        }

        .loading-spinner {
            display: inline-block;
            width: 32px;
            height: 32px;
            border: 3px solid #e2e8f0;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
            margin-bottom: 16px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .hidden {
            display: none !important;
        }

        /* 响应式设计 */
        @media (max-width: 480px) {
            .share-card {
                padding: 32px 24px;
            }

            .title {
                font-size: 20px;
            }

            .password-input {
                width: 50px;
                height: 50px;
                font-size: 24px;
            }

            .file-icon {
                font-size: 48px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="share-card">
            <div class="header">
                <h1 class="title">文件分享</h1>
                <p class="subtitle">请输入4位数字密码查看分享内容</p>
        </div>

            <!-- 密码验证表单 -->
            <div id="passwordForm" class="password-form">
                <div class="password-inputs">
                    <input type="text" class="password-input" id="pwd1" maxlength="1" pattern="[0-9]" autocomplete="off" inputmode="numeric">
                    <input type="text" class="password-input" id="pwd2" maxlength="1" pattern="[0-9]" autocomplete="off" inputmode="numeric">
                    <input type="text" class="password-input" id="pwd3" maxlength="1" pattern="[0-9]" autocomplete="off" inputmode="numeric">
                    <input type="text" class="password-input" id="pwd4" maxlength="1" pattern="[0-9]" autocomplete="off" inputmode="numeric">
                </div>
                <button class="btn btn-primary" onclick="verifyPassword()">验证密码</button>
            </div>

            <!-- 错误提示 -->
            <div id="errorMessage" class="error-message hidden no-share"></div>

            <!-- 加载状态 -->
            <div id="loadingState" class="loading hidden">
                <div class="loading-spinner"></div>
                <div>正在验证...</div>
            </div>

            <!-- 文件信息 -->
            <div id="fileInfo" class="hidden">
                <div class="file-info">
                    <span class="file-icon" id="fileIcon">📄</span>
                    <div class="file-name" id="fileName">文件名</div>
                    <div class="file-meta">
                        <span id="fileSize">文件大小</span>
                        <span>•</span>
                        <span id="fileDate">创建时间</span>
                    </div>
            </div>

                <!-- 有效期信息 -->
                <div id="expireInfo" class="expire-info">
                    <span id="expireText">有效期信息</span>
            </div>

                <!-- 下载按钮 -->
                <button id="downloadBtn" class="download-btn" onclick="downloadFile()">
                    <span>📥</span> 下载文件
                </button>
            </div>
        </div>
    </div>

    <script>
        // 获取分享码
        const shareCode = window.location.pathname.split('/').pop();
        let shareData = null;
        
        // 页面加载完成后自动验证
        document.addEventListener('DOMContentLoaded', function() {
            checkShareStatus();
            setupPasswordInputs();
        });

        // 设置密码输入框
        function setupPasswordInputs() {
            const inputs = ['pwd1', 'pwd2', 'pwd3', 'pwd4'];
            
            inputs.forEach((id, index) => {
                const input = document.getElementById(id);
                
                // 只允许输入数字
                input.addEventListener('input', function(e) {
                    e.target.value = e.target.value.replace(/[^0-9]/g, '');
                    
                    // 自动跳转到下一个输入框
                    if (e.target.value && index < inputs.length - 1) {
                        document.getElementById(inputs[index + 1]).focus();
                    }
                    
                    // 如果4位都填满，自动验证
                    if (index === inputs.length - 1 && e.target.value) {
                        const allFilled = inputs.every(id => document.getElementById(id).value);
                        if (allFilled) {
                            setTimeout(() => verifyPassword(), 300);
                        }
                    }
                });
                
                // 退格键处理
                input.addEventListener('keydown', function(e) {
                    if (e.key === 'Backspace' && !e.target.value && index > 0) {
                        document.getElementById(inputs[index - 1]).focus();
                    }
                });
            });
        }

        // 检查分享状态
        async function checkShareStatus() {
            try {
                const response = await fetch(`/api/share/access/${shareCode}`);
                const result = await response.json();
                
                if (result.success) {
                    const data = result.data;
                    
                    if (data.requiresPassword) {
                        // 需要密码验证，显示密码输入表单
                        document.getElementById('passwordForm').classList.remove('hidden');
                        document.getElementById('errorMessage').classList.add('hidden');
                        const subtitleElement = document.querySelector('.header .subtitle');
                        if (subtitleElement) {
                            subtitleElement.textContent = '请输入4位数字密码查看分享内容';
                        }
                    } else {
                        // 不需要密码，直接加载文件
                        shareData = data;
                        document.getElementById('passwordForm').classList.add('hidden');
                        document.getElementById('errorMessage').classList.add('hidden');
                        loadShareFiles();
                    }
                } else {
                    // 分享不存在或已过期，隐藏密码表单，只显示错误
                    document.getElementById('passwordForm').classList.add('hidden');
                    document.getElementById('header').classList.add('hidden');
                    showError(result.message || '分享不存在');
                }
            } catch (error) {
                console.error('检查分享状态失败:', error);
                // 网络错误时也隐藏密码表单
                document.getElementById('passwordForm').classList.add('hidden');
                document.getElementById('header').classList.add('hidden');
                showError('网络错误，请稍后重试');
            }
        }

        // 验证密码
        async function verifyPassword() {
            const password = document.getElementById('pwd1').value + 
                           document.getElementById('pwd2').value + 
                           document.getElementById('pwd3').value + 
                           document.getElementById('pwd4').value;
            
            if (password.length !== 4) {
                showError('请输入完整的4位数字密码');
                return;
            }

            try {
                showLoading();
                hideError();

                const response = await fetch(`/api/share/verify/${shareCode}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ password: password })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const result = await response.json();

                if (result.success) {
                    shareData = result.data;
                    setTimeout(() => loadShareFiles(), 200);
                } else {
                    showError(result.message || '密码错误');
                    clearPasswordInputs();
                }
            } catch (error) {
                console.error('验证密码失败:', error);
                showError('网络错误，请稍后重试');
            } finally {
                hideLoading();
            }
        }

        // 清空密码输入框
        function clearPasswordInputs() {
            ['pwd1', 'pwd2', 'pwd3', 'pwd4'].forEach(id => {
                document.getElementById(id).value = '';
            });
            document.getElementById('pwd1').focus();
        }

        // 加载分享文件
        function loadShareFiles() {
            if (!shareData) {
                showError('分享数据不存在');
                return;
            }

            document.getElementById('passwordForm').classList.add('hidden');
            hideLoading();
            hideError();
            displayFileInfo();
        }

        // 显示文件信息
        function displayFileInfo() {
            const file = shareData.files && shareData.files[0] ? shareData.files[0] : null;
            
            if (!file) {
                showError('文件信息不存在');
                return;
            }
            
            document.getElementById('fileIcon').textContent = getFileIcon(file.fileName, file.isDirectory);
            document.getElementById('fileName').textContent = file.fileName || '未知文件';
            document.getElementById('fileSize').textContent = formatFileSize(file.fileSize || 0);
            document.getElementById('fileDate').textContent = formatDate(shareData.shareInfo ? shareData.shareInfo.createTime : null);

            updateExpireInfo();
            document.getElementById('fileInfo').classList.remove('hidden');
            
            // 更新标题
            const subtitleElement = document.querySelector('.header .subtitle');
            if (subtitleElement) {
                subtitleElement.textContent = '文件分享中';
            }
        }

        // 更新有效期信息
        function updateExpireInfo() {
            const expireInfo = document.getElementById('expireInfo');
            const expireText = document.getElementById('expireText');
            
            const expireTime = shareData.shareInfo ? shareData.shareInfo.expireTime : shareData.expireTime;
            
            if (expireTime) {
                const expireDate = new Date(expireTime);
                const now = new Date();
                
                if (expireDate <= now) {
                    expireInfo.classList.add('expired');
                    expireText.textContent = '⚠️ 此分享已过期';
                    document.getElementById('downloadBtn').disabled = true;
                } else {
                    const diffTime = expireDate - now;
                    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
                    
                    if (diffDays === 1) {
                        expireText.textContent = '⏰ 此分享将于明天过期';
                    } else if (diffDays <= 7) {
                        expireText.textContent = `⏰ 还有 ${diffDays} 天过期`;
                    } else {
                        expireText.textContent = `📅 有效期至 ${expireDate.toLocaleDateString('zh-CN')}`;
                    }
                }
            } else {
                expireText.textContent = '♾️ 永久有效';
            }
        }

        // 下载文件
        function downloadFile() {
            if (!shareData || !shareData.files || shareData.files.length === 0) {
                showError('文件信息不存在');
                return;
            }

            const file = shareData.files[0];
            if (file.isDirectory) {
                showError('文件夹无法下载');
                return;
            }

            const fileId = shareData.shareInfo ? shareData.shareInfo.fileId : null;
            if (!fileId) {
                showError('文件ID不存在');
                return;
            }

            window.location.href = `/api/share/download/${shareCode}/${fileId}`;
        }

        // 显示加载状态
        function showLoading() {
            document.getElementById('loadingState').classList.remove('hidden');
            document.getElementById('passwordForm').classList.add('hidden');
            document.getElementById('fileInfo').classList.add('hidden');
        }

        // 隐藏加载状态
        function hideLoading() {
            document.getElementById('loadingState').classList.add('hidden');
        }

        // 显示错误信息
        function showError(message) {
            const errorElement = document.getElementById('errorMessage');
            errorElement.textContent = message;
            errorElement.classList.remove('hidden');
            hideLoading();
            // 确保其他区域都隐藏
            document.getElementById('passwordForm').classList.add('hidden');
            document.getElementById('fileInfo').classList.add('hidden');
        }

        // 隐藏错误信息
        function hideError() {
            document.getElementById('errorMessage').classList.add('hidden');
        }

        // 获取文件图标
        function getFileIcon(fileName, isDirectory) {
            if (isDirectory) return '📁';
            if (!fileName) return '📄';
            
            const ext = fileName.split('.').pop().toLowerCase();
            const iconMap = {
                'pdf': '📄', 'doc': '📝', 'docx': '📝',
                'xls': '📊', 'xlsx': '📊', 'ppt': '📋', 'pptx': '📋',
                'txt': '📄', 'jpg': '🖼️', 'jpeg': '🖼️', 'png': '🖼️', 'gif': '🖼️',
                'mp4': '🎥', 'avi': '🎥', 'mov': '🎥',
                'mp3': '🎵', 'wav': '🎵',
                'zip': '📦', 'rar': '📦', '7z': '📦'
            };
            
            return iconMap[ext] || '📄';
        }

        // 格式化文件大小
        function formatFileSize(size) {
            if (!size || size === 0) return '-';
            
            const units = ['B', 'KB', 'MB', 'GB'];
            let unitIndex = 0;
            let formattedSize = size;
            
            while (formattedSize >= 1024 && unitIndex < units.length - 1) {
                formattedSize /= 1024;
                unitIndex++;
            }
            
            return formattedSize.toFixed(1) + ' ' + units[unitIndex];
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '-';
            
            try {
                const date = new Date(dateString);
                return date.toLocaleDateString('zh-CN');
            } catch (error) {
                return dateString;
            }
        }
    </script>
</body>
</html>
